angular.module('mamApp').controller('programmeEditController', ['$scope', '$state', 'AlbumManager', 'FileUploader', '$uibModal', 'api', 'ProgramsManager', 'ChannelManager', '$filter', '$sce','BaseValidations','ImsErr',
    function ($scope, $state, AlbumManager, FileUploader, $uibModal, api, ProgramsManager, ChannelManager, $filter, $sce,BaseValidations,ImsErr) {
        var albumId = $state.params.albumId;
        $scope.programId = $state.params.programId;
        $scope.BaseValidations = BaseValidations;
        $scope.album = {commonTagsSelected: [], specialTagsSelected: []};
        $scope.image_a = false;

        $scope.$sce = $sce;
        $scope.disabled = false;
        $scope.formData = {};


        $scope.list = [];

        ChannelManager.commTagsList().then(function (result) {
            $scope.commonTags = [];
            $scope.commonDimensionsName = {};
            result.data.list.forEach(function (item) {
                $scope.commonDimensionsName[item.dimensionId] = item.dimensionsName;
                if (item.hasOwnProperty("list")) {
                    item.list.forEach(function (tag) {
                        $scope.commonTags.push({
                            commtagId: tag.commtagId,
                            dimensionId: item.dimensionId,
                            commtagName: tag.commtagName
                        })
                    })
                }
            })


        })


        $scope.specialTagsList = function (channelId) {
            $scope.specialTags = [];
            $scope.specialDimensionsName = {};

            ChannelManager.specialTagsList(channelId).then(function (result) {
                if (result.data.list) {
                    result.data.list.forEach(function (item) {
                        $scope.specialDimensionsName[item.dimensionId] = item.dimensionsName;

                        if (item.hasOwnProperty("list")) {
                            item.list.forEach(function (tag) {
                                $scope.specialTags.push({
                                    specialId: tag.specialId,
                                    dimensionId: tag.dimensionId,
                                    specialName: tag.specialName
                                })
                            })
                        }

                    })
                }


            })
        }

        /**
         * 专辑改变请求详细信息
         * @param album
         */

        $scope.albumChange = function (album) {
            AlbumManager.albumDetail(album.albumId).then(function (result) {
                $scope.albumData = result.data.cpAlbumVO;
                $scope.specialTagsList($scope.albumData.channelId)

                var tmpComm = [];
                var tmpSpe = [];

                $scope.albumData.commList.forEach(function (tag) {
                    tmpComm.push({
                        commtagId: tag.commtagId,
                        dimensionId: tag.dimensionId,
                        commtagName: tag.commtagName
                    })
                })
                $scope.albumData.specialList.forEach(function (tag) {
                    tmpSpe.push({
                        specialId: tag.specialId,
                        dimensionId: tag.dimensionId,
                        specialName: tag.specialName
                    })
                })
                $scope.album.commonTagsSelected = tmpComm;
                $scope.album.specialTagsSelected = tmpSpe;
                $scope.formData.programCover = $scope.albumData.albumCover;
                $scope.formData.keyword = $scope.albumData.keyword;
                $scope.formData.anchorName = $scope.albumData.anchorName;
                $scope.formData.originalName = $scope.albumData.originalName;
                $scope.formData.summary = $scope.albumData.summary;


            })
        }

        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.commGroupFn = function (item) {
            return $scope.commonDimensionsName[item.dimensionId]
        };
        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.specialGroupFn = function (item) {
            return $scope.specialDimensionsName[item.dimensionId]
        };

        AlbumManager.albumList([1, 100]).then(function (result) {
            $scope.albumList = result.data.pageList;
            if (albumId) {
                $scope.album.albumSelected = $filter('filter')($scope.albumList, {albumId: albumId})[0];
                $scope.specialTagsList($scope.album.albumSelected.channelId)

            }


        });


        if ($scope.programId) {
            ProgramsManager.programDetail($scope.programId).then(function (result) {
                $scope.formData = result.data.cpProgramVO;
                $scope.formData.keyword = $scope.formData.keyword.join(",")
                var tmpComm = [];
                var tmpSpe = [];

                $scope.formData.commList.forEach(function (tag) {
                    tmpComm.push({
                        commtagId: tag.commtagId,
                        dimensionId: tag.dimensionId,
                        commtagName: tag.commtagName
                    })
                })
                $scope.formData.specialList.forEach(function (tag) {
                    tmpSpe.push({
                        specialId: tag.specialId,
                        dimensionId: tag.dimensionId,
                        specialName: tag.specialName
                    })
                })
                $scope.album.commonTagsSelected = tmpComm;
                $scope.album.specialTagsSelected = tmpSpe;
            })
        }


        $scope.myImage = '';
        $scope.myCroppedImage = '';

        var handleFileSelect = function (evt) {
            var file = evt.currentTarget.files[0];

            $scope.uploadCover(file);

        };

        setTimeout(function () {
            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        }, 1000)

        $scope.uploadCover = function (image) {
            if(image.type.indexOf("image")==-1){
                $scope.$apply($scope.errorImg='仅支持PNG/JPG/JPEG格式');
                return false;
            }else {
                $scope.$apply($scope.errorImg='');
            }
            var modalInstance = $uibModal.open({
                animation: true,
                backdrop:false,
                templateUrl: 'uploadCover.html',
                controller: 'coverManageController',
                resolve: {
                    params: function () {
                        return {image: image,coverType:"program"};
                    }
                }
            });
            modalInstance.result.then(function (result) {
                $("#fileInput").prop("value","");

                if (result.url) {
                    $scope.formData.programCover = result.url;

                }

            })
        }



        $scope.search = {
            status: $state.params.status
        };

        $scope.tabClick = function (index) {
            if ($scope.programId) {
                return false;
            }
            $scope.search.status = index;
            $state.go($state.current.name, $scope.search);
        };

        $scope.uploaderAudio = new FileUploader({
            alias: "uploadFile",
            queueLimit: $scope.search.status == "single" || !$scope.search.status ? 1 : 20,//文件个数
            // removeAfterUpload: true,//上传后删除文件 */
            filters: [{
                name: 'uploadFile',//后台接收字段
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    if (!/\.(mp3|MP3|AAC|aac)$/.test(item.name)) {
                        $scope.imageMsg = "最多只能上传" + 20 + "条mp3或者AAC格式且每个小于" + 150 + "MB的音频";
                        $scope.image_a = true;
                        return false;
                    }
                    else if (item.size > 150 * 1024 * 1024||item.size < 0.5 * 1024 * 1024) {
                        $scope.imageMsg = "最多只能上传" + 20 + "条mp3或者AAC格式且每个小于" + 150 + "MB的音频";
                        $scope.image_a = true;
                        return false;
                    } else {
                        $scope.image_a = false;
                        return true;
                    }
                }
            }],
            onSuccessItem: function (fileItem, response, headers) {
                if (response.c == "s") {
                    delete  response.c;
                    $scope.list.push({file: response.fileVO, audio: response.audioInfoVO});
                } else {
                    fileItem.isSuccess = 'uploadFail';
                }
            },
            url: api + "/cp/programs/audio",
            headers: {'X-Auth-Token': $scope.userInfo.token}
        });

        $scope.uploadAllAudio = function () {
            $scope.uploaderAudio.uploadAll();
        };


        $scope.programmeEdit = function () {
            $scope.disabled = true;
            var file = {
                "filePath": $scope.formData.origAudioFilePath,
                "webUrl": $scope.formData.origAudioUrl,
                "fileOrigName": $scope.formData.origAudioName,
                "fileSize": $scope.formData.origAudioFileSize
            };
            var audio = {
                "duration": $scope.formData.origAudioDuration,
                "bitRate": $scope.formData.origAudioBitRate,
                "channels": $scope.formData.origAudiochannels,
                "samplingRate": $scope.formData.origAudioSamplingRate
            }
            var commTag = [];
            var specialTag = [];
            $scope.album.commonTagsSelected.forEach(function (item) {
                commTag.push(item.commtagId)
            })
            $scope.album.specialTagsSelected.forEach(function (item) {
                specialTag.push(item.specialId)
            })


            var tmpToSave = {
                albumId: $scope.formData.albumId,
                programId: $scope.formData.programId,
                programName: $scope.formData.programName,
                isExtend: $scope.formData.isExtend,
                programCover: $scope.formData.programCover,
                commTag: commTag.join(","),
                specialTag: specialTag.join(","),
                keyword: $scope.formData.keyword?$scope.formData.keyword.split(","):[],
                anchorName: $scope.formData.anchorName,
                originalName: $scope.formData.originalName,
                summary: $scope.formData.summary,
                file: $scope.list.length ? $scope.list[0].file : file,
                audio: $scope.list.length ? $scope.list[0].audio : audio
            };

            ProgramsManager.programEdit($scope.programId, tmpToSave).then(function (result) {
                $scope.disabled = false;
                if (result.data.c == "s") {
                    $state.go("main.album.info", {albumId: $scope.formData.albumId}, {reload: true})
                }else {
                    $scope.formData.keyword = $scope.formData.keyword.join(",")
                    ImsErr.open({message:result.data.i}).then(function (a) {
                    })
                }
            })
        };


    }]);

